package com.hotel.BL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;

import data.POSGuestTable;
import data.POSHistory;

public class POSHistoryLogic extends AbstractBL {
	
	private HttpSession session;
	
	public POSHistoryLogic(HttpServletRequest req,HttpServletResponse resp)
	{
		this.session = req.getSession(true);
		this.req = req;
		this.resp = resp;
	}
	
	public POSGuestTable CreatePOSTable(POSGuestTable posGuestTable) throws EntityNotFoundException{
		return LogPOSHistory(posGuestTable,"Create","Create POSGuestTable");
	}
	
	public POSGuestTable ReservePOSTable(POSGuestTable posGuestTable) throws EntityNotFoundException{
		return LogPOSHistory(posGuestTable,"Create","Create POSGuestTable");
	}
	
	public POSGuestTable OrderGuestTable(POSGuestTable posGuestTable) throws EntityNotFoundException{
		return LogPOSHistory(posGuestTable,"Create Order","Order");
	}
	
	public POSGuestTable OrderEditAmountItem(POSGuestTable posGuestTable) throws EntityNotFoundException{
		return LogPOSHistory(posGuestTable,"Edit","Edit Amount Item");
	}
	
	public POSGuestTable OrderEditDiscountItem(POSGuestTable posGuestTable) throws EntityNotFoundException{
		return LogPOSHistory(posGuestTable,"Edit","Edit Discount Item");
	}
	
	public POSGuestTable AddNote(POSGuestTable posGuestTable,String title) throws EntityNotFoundException{
		return LogPOSHistory(posGuestTable,"Note",title);
	}
	
	private POSGuestTable LogPOSHistory(POSGuestTable posGuestTable,String change,String title) throws EntityNotFoundException{
		POSHistory posHistory = new POSHistory();
		GenericLogic gLogic = new GenericLogic(req,resp);
		
		posHistory.setTitle(title);
		posHistory.setChange(change);
		posHistory.setUser((String) session.getAttribute("user"));
		posHistory.setStampDate(gLogic.ServerDateTime());
		
		Key key = datastore.put(posHistory.getEntity());
		posHistory.setId(key.getId());
		posHistory.setKey(key);
		
		posGuestTable.addPOSHistory(posHistory);
		return posGuestTable;
	}
	
	public long CountHistory(POSGuestTable posGuestTable){
		String listString = posGuestTable.getPOSHistoryListString();
		String[] ids = listString.split(",");
		return ids.length;
	}
}
